import classnames from 'classnames'
import { useEffect, useRef, useState } from 'react'
import Icon from './Icon'
import styles from './index.module.scss'

/**
 * 拥有懒加载特性的图片组件
 * @param {String} props.src 图片地址
 * @param {String} props.className 样式类
 */
type Props = {
  src: string
  className?: string
}
const Image = ({ src, className, ...rest }: Props) => {
    // 对图片元素的引用
    const imgRef = useRef<HTMLImageElement>(null)
    // 正在加载时显示的内容
    const [loading, setLoading] = useState(true)
    // 错误时显示错误的内容
    const [error, setError] = useState(false)
    useEffect(() => {
      const ob = new IntersectionObserver(
        (entries) => {
          console.log('working....')
          if (entries[0].isIntersecting) {
            imgRef.current!.src = src
            ob.unobserve(imgRef.current!) 
          }
        },
        { rootMargin: '300px' }
      )
        ob.observe(imgRef.current!)
      return () => {
        ob.disconnect() //停止观察者
      }
    }, [src])
  
    return (
      <div className={classnames(styles.root, className)}>
        {/* 正在加载时显示的内容 */}
        {loading && (
          <div className="image-icon">
            <Icon type="iconphoto" />
          </div>
        )}
  
        {/* 加载出错时显示的内容 */}
        {error && (
          <div className="image-icon">
            <Icon type="iconphoto-fail" />
          </div>
        )}
  
        {/* 加载成功时显示的内容 */}
        {
          <img
            {...rest}
            alt=""
            onError={() => setError(true)}
            onLoad={() => setLoading(false)}
            data-src={src}
            ref={imgRef}
          />
        }
      </div>
    )
  }
  
  export default Image